<?php

namespace App\Http\Controllers\Admin;

use App\Models\GoodsType;
use App\Models\Spec;
use App\Models\SpecValue;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * 规格控制器
 * @package App\Http\Controllers\Admin
 */
class SpecController extends Controller
{
	/**
	 * 规格列表
	 * User: Clannad ~ ☆
	 * DataTime：2019/11/15 12:24
	 */
	public function index($id)
    {
		$specList = Spec::query()
				->orderBy('id','desc')
				->where(['type_id'=>$id])
				->paginate(10);

		return view('admin.spec.index',compact('specList'));
    }


	public function create()
    {
    	//规格有属于分类，所以，要有个分类
		$typeList = GoodsType::query()
					->select('type_name','id')
					->get()
					->toArray();
		return view('admin.spec.create',compact('typeList'));
    }


	public function store(Request $request, Spec $spec)
	{
		$insertData = $request->except(['_token']);

		$spec->fill($insertData);
		$spec->save();

		return redirect()->route('admin.spec.index',['id'=>$insertData['type_id']])->with('success','添加规格成功');
    }


	public function edit(Request $request,$id)
	{
		$spec = Spec::findOrfail($id);

		$typeList = GoodsType::query()
			->select('type_name','id')
			->get()
			->toArray();

		return view('admin.spec.edit',compact('spec','typeList'));
    }


	public function update(Request $request,$id)
	{
		$spec = Spec::findOrFail($id);

		$insertData = $request->except(['_token']);

		$spec->fill($insertData);
		$spec->update();

		return redirect()->route('admin.spec.index',['id'=>$insertData['type_id']])->with('success','修改规格成功');
    }


	public function destroy($id)
    {
		$spec = Spec::findOrfail($id);
		//销毁类型的时候，要判断有没有属性在用，在用的不可删除。
		$spec_value = SpecValue::query()->where('spec_id',$id)->count();
		if($spec_value){
			return back()->with('danger','该商品规格有规格属性在使用，请先删除在用的属性');
		}

		$type_id = $spec->type_id;

		$spec->delete();

		return redirect()->route('admin.goods_spec.index',['id'=>$type_id])->with('success','删除成功');
    }

}
